<?php

namespace app\common\model;
use wxopen\WxComponentService;

/**
 * 签到模型
 */
class Signin extends Base{
	
	public function action() {
		if(session('user_auth.uid')){
			$uid = session('user_auth.uid');
			$qinfo = db('qiandao')->where('user_id',$uid)->order('qiandao_time desc')->limit(1)->find();
			
			
			if(date('Y-m-d',time()) == date('Y-m-d',$qinfo['last_qiandao'])){
				return 1;
			}else{
				$days = $this->getYesterdayDays($uid);
				$jinbi =config('qbegold');
				

				//写入签到表
				$data['user_id']=session('user_auth.uid');
				$data['last_qiandao']=time();
				$data['count_qiandao']=$days;
				$data['qiandao_time']= time();
				$data['jinbi']=$jinbi;
				$data['xingqi']=date('w',time());
				db('qiandao')->insert($data);
				//赠送金币明细
				$expire = strtotime(date('Y-m-d'))+config('sign_expire')*24*3600;
				$point=array(
					'uid'=>session('user_auth.uid'),
					'egold'=>$jinbi,
					'add_time'=>time(),
					'expire_time'=>$expire
				);
				db('member_point')->insert($point);
				//更新用户表
				db('member')->where('uid',session('user_auth.uid'))->update(array('sign_score'=>['exp','sign_score+'.$jinbi]));
				//增加充值记录
				$log['user_id'] =session('user_auth.uid');
				$log['type'] =4;
				$log['title'] ="签到赠送";
				$log['money'] =0;
				$log['shubi'] =$jinbi;
				$log['created_at'] =time();
				db('chongzhi_log')->insert($log);
				$this->signreply();
				return true;
			}
		}
		return 'null';
	}
	
	// 昨天的连续签到天数
	protected function getYesterdayDays($uid){
		// 昨天的连续签到天数
		$start_time  = mktime(0,0,0,date('m'),date('d')-1,date('Y'));
		$end_time = mktime(0,0,0,date('m'),date('d'),date('Y'))-1;

		$days = db('qiandao')->where("user_id = ".$uid." and qiandao_time >= ".$start_time." and qiandao_time <= ".$end_time)->value('count_qiandao');

		if($days){
		  $days++;
		  if($days > 7){
			$days = 1;
		  }
		}else{
		  $days = 1;
		}
		return $days;
	}

	/*****签到回复******/
	protected function signreply() {

		$host = explode('.',$_SERVER['HTTP_HOST']);
		$auto = array();
		if(strpos($host[0],'t') !==false){
			$uid = split_host($host[0]);
			$wxmpid= split_host($host[0],2);
			
			$intelligent = db('wechat_intelligent')->where(['uid'=>$uid,'wxmpid'=>$wxmpid,'type'=>4,'open'=>1])->find();
			if(empty($intelligent)){
				return true;
			}
			
			$auto = db('wxmp')->where(['id'=>$wxmpid,'status'=>1])->field('appid,autoconfig,open_appid')->find();
			//公众号自动配置
			if($auto["autoconfig"]){
				$account = db('wxopen_account')->where('appid',$auto['open_appid'])->find();
				$wxComponentConfig = array(
					'component_appid'=>$account["appid"],
					'component_appsecret'=>$account["appsecret"],
					'encodingAesKey'=>$account["encodingKey"],
					'token'=>$account["token"]
				);
				$site_url =get_menuurl($uid,$wxmpid);
			}else{
				$wxmp = 1;
				$site_url = config('web_site_url');
			}
		}else{
			$intelligent = db('wechat_intelligent')->where(['uid'=>1,'wxmpid'=>0,'type'=>4,'open'=>1])->find();
			if(empty($intelligent)){
				return true;
			}
			$wxmp = 1;
			$site_url = config('web_site_url');
		}
		$uid = session('user_auth.uid');
		
		//获取阅读记录
		$history = array();
		$frist = null;
		$other = null;

		$history = db('history')->alias('h')->join('__NOVEL__ n ','h.articleid=n.id','INNER')->where(array('h.uid'=>session('user_auth.uid'),'h.model'=>1,"n.status"=>1,"n.display"=>1))->order('h.update_time DESC')->group('h.articleid')->field("h.*")->limit(6)->select();
		
		if($history){
			foreach ($history as $k=>$v){
				if($k==0){
					//$frist = emoji("\ue231").'<a href="'.$site_url.'/chapter/read/'.$v['articleid'].'/'.$v['chapterid'].'">点我继续上次阅读</a>';
					$frist = emoji("\ue231").'<a href="'.$site_url.'/focushistory?focus=true">点我继续上次阅读</a>';

				}
				$other .=emoji("\ue231").'<a href="'.$site_url.'/chapter/read/'.$v['articleid'].'/'.$v['chapterid'].'">'.$v['name'].'</a>'.PHP_EOL.PHP_EOL;
			}
		}
		
		if(empty($history)){
			$clicktop = db('novel')->where(array('status'=>1,''=>['exp','FIND_IN_SET(3,is_top)']))->field('id,title')->order('create_time DESC')->limit(4)->select();
			if($clicktop){
				foreach ($clicktop as $k=>$v){
					$other .=emoji("\ue231").'<a href="'.$site_url.'/book/info/id/'.$v['id'].'">'.$v['title'].'</a>'.PHP_EOL.PHP_EOL;
				}
			}
		}

		$openid = db('MemberUserapi')->where(array('uid'=>$uid))->value('wxmpid');
		
		
		if($openid){
			$tyname = $history?"阅读记录":"小说精选";
			$template = array(
				"touser"=>$openid,
				"msgtype"=>"text",
				"text"=>array('content'=>'今日签到成功，赠送'.config('qbegold').'书币,明日继续签到得书币哦~'.PHP_EOL.PHP_EOL.$frist.PHP_EOL.PHP_EOL.emoji("\ue003").$tyname.':'.PHP_EOL.$other.emoji("\ue003").'为方便下次阅读，请置顶公众号'),
			);
			
			if($auto&&$auto["autoconfig"]){
				$wxAuth = new WxComponentService($wxComponentConfig);
				$weObj = $wxAuth->getWechat($auto['appid']);
				$weObj->sendCustomMessage($template);
			}else{
				$receive = &load_wechat($wxmp,'Receive');
				$receive->sendCustomMessage($template);
			}
			
		}
	}

}